package edu.xidian.forum.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.vdurmont.emoji.EmojiParser;
import edu.xidian.forum.common.Result;
import edu.xidian.forum.dto.CreateTopicDto;
import edu.xidian.forum.dto.UpdateTopicDto;
import edu.xidian.forum.entity.*;
import edu.xidian.forum.service.*;
import edu.xidian.forum.vo.PostVO;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Lazy;
import org.springframework.util.ObjectUtils;
import org.springframework.web.bind.annotation.*;

import javax.validation.Valid;
import java.util.Date;
import java.util.List;
import java.util.Map;

import static edu.xidian.forum.jwt.JwtUtil.USER_NAME;


@RestController
@RequestMapping("/post")
public class PostController {

    @Autowired
    private UserService userService;
    @Autowired
    private PostService postService;
    @Autowired
    private FavoriteService favoriteService;
    @Autowired
    @Lazy
    private TagService tagService;
    @Autowired
    private TopicTagService topicTagService;

    @PostMapping("/create")
    public Result<Post> create(@RequestHeader(value = USER_NAME) String userName
            , @RequestBody CreateTopicDto dto) {
        User user = userService.getUser(userName);
        Post post = postService.create(dto, user);
        return Result.success(post);
    }

    @DeleteMapping("/delete")
    public Result<String> delete(@RequestHeader(value = USER_NAME) String userName, @RequestParam("id") String id) {
        User user = userService.getUser(userName);
        Post post = postService.getById(id);
        if (ObjectUtils.isEmpty(post)) {
            return Result.failed("The topic doesn't exist");
        }
        if (user.getRoleId() != 1 && !post.getUserId().equals(user.getId())) {
            return Result.failed("Why can you delete other's topic?");
        }
        postService.removeById(id);
        return Result.success("Successfully delete", null);
    }

    @GetMapping()
    public Result<Map<String, Object>> get(@RequestParam("id") String id) {
        Post topic = postService.getById(id);
        if (ObjectUtils.isEmpty(topic)) {
            return Result.failed("The current topic does not exist or has been deleted by the author");
        }
        Map<String, Object> map = postService.viewTopic(id);
        return Result.success(map);
    }

    @PutMapping("/update")
    public Result<Void> update(@RequestHeader(value = USER_NAME) String userName, @Valid @RequestBody UpdateTopicDto dto) {
        Post post = postService.getById(dto.getId());
        if (post == null) {
            return Result.failed("Post not found");
        }
        User user = userService.getUser(userName);
        if (!user.getId().equals(post.getUserId())) {
            return Result.failed("Have no right to modify");
        }

        post.setTitle(dto.getTitle());
        post.setContent(EmojiParser.parseToAliases(dto.getContent()));
        post.setModifyTime(new Date());
        postService.updateById(post);

        if (!ObjectUtils.isEmpty(dto.getTags())) {
            List<Tag> tags = tagService.insertTags(dto.getTags());
            topicTagService.remove(Wrappers.<TopicTag>lambdaQuery().eq(TopicTag::getTopicId, post.getId()));
            topicTagService.createTopicTag(post.getId(), tags);
        }

        return Result.success();
    }

    @GetMapping("/list")
    public Result<Page<PostVO>> list(@RequestBody @RequestParam(value = "userid", defaultValue = "visitor") String user_id,
                                     @RequestBody @RequestParam(value = "tab", defaultValue = "latest") String tab,
                                     @RequestBody @RequestParam(value = "pageNo", defaultValue = "1") Integer pageNo,
                                     @RequestBody @RequestParam(value = "size", defaultValue = "10") Integer pageSize) {

        Page<PostVO> list = postService.getList(new Page<>(pageNo, pageSize), tab, user_id);
        return Result.success(list);
    }

    @GetMapping("/recommend")
    public Result<List<Post>> getRecommend(@RequestParam("topicId") String id) {
        List<Post> topics = postService.getRecommend(id);
        return Result.success(topics);
    }

    @GetMapping("/like")
    public Result<Favorite> getlike(@RequestHeader(value = USER_NAME) String userName,
                                    @RequestBody @RequestParam("topic_id") String topic_id) {
        User user = userService.getUser(userName);
        Favorite favorite = favoriteService.like(user, topic_id);

        return Result.success(favorite);
    }

    @GetMapping("/unlike")
    public Result<Object> getunlike(@RequestHeader(value = USER_NAME) String userName,
                                    @RequestBody @RequestParam("topic_id") String topic_id) {
        User user = userService.getUser(userName);
        Favorite favorite = favoriteService.getOne(new LambdaQueryWrapper<Favorite>()
                .eq(Favorite::getUserId, user.getId())
                .eq(Favorite::getTopicId, topic_id));
        favoriteService.unlike(favorite);
        return Result.success(1);
    }

    @GetMapping("/hasliked")
    public Result<Favorite> hasliked(@RequestHeader(value = USER_NAME) String userName,
                                     @RequestBody @RequestParam("topic_id") String topic_id) {
        User user = userService.getUser(userName);

        return Result.success(favoriteService.hasliked(user, topic_id));
    }
}

